package com.zntg.pdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.zntg.bo.FundFeneSureBook;
import com.zntg.contants.FundFeneSureBookContants;
import com.zntg.utils.DateUtil;
import com.zntg.utils.FileUtils;
import com.zntg.utils.MoneyTool;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
 * @program: 净值类产品认购书申请功能
 * @description:对应ods库T_SPCI_PROD这张表的SPCI_TYE = '1'的份额确认书生成功能
 * @author: zhengyunfei
 * @create: 2018-12-03 09:20
 **/
public class CreatePdfUtilTemplate1 {
    /**
    * @Description: 净值类产品
    * @Author: zhengyunfei
    * @Date: 2019/4/12
    * @time:17:49
    */
    public static FundFeneSureBook createPdf(FundFeneSureBook fundFeneSureBook) throws IOException, DocumentException {
        // pdf模板
      /*  String fileName = "D:\\work\\ylcaifu\\智能投顾二期\\报表平台\\pdf生成好的不带logo的模板\\优策月月盈3号份额确认书-（追加申购模板）2.pdf";*/
        String fileName=fundFeneSureBook.getSourcePath();
        PdfReader reader = new PdfReader(fileName);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /* 将要生成的目标PDF文件名称 */
        PdfStamper ps = new PdfStamper(reader, bos);
        PdfContentByte under = ps.getUnderContent(1);
        /* 使用中文字体 */
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);
        /* 取出报表模板中的所有字段 */
        AcroFields fields = ps.getAcroFields();

        fields.setSubstitutionFonts(fontList);
        fillData(fields, jingZhiProdData(fundFeneSureBook));
        /* 必须要调用这个，否则文档不会生成的 */
        ps.setFormFlattening(true);
        ps.close();
        //获取当天日期
        String today= DateUtil.getToDay();
        String l_storageid=fundFeneSureBook.getlStorageid();
        String targetPath=fundFeneSureBook.getTargetPath();
        String path=targetPath+today;
        boolean flag=FileUtils.mkdir(path);
        if(!flag){
            path=path+"\\Tblobstorage";
         //   file=new File(path);
            flag=FileUtils.mkdir(path);
        }else{
            path=path+"\\Tblobstorage";
        }
        String lStorageId=l_storageid.substring(0,l_storageid.length()-1);
        path=path+"\\"+lStorageId;
        FileUtils.mkdir(path);
        String createTofileName=l_storageid+"baccessory";
        FileUtils.createParentDir(path+"\\"+createTofileName);
        //生成pdf路径
        OutputStream fos = new FileOutputStream(path+"\\"+createTofileName);
        fos.write(bos.toByteArray());
        fos.flush();
        fos.close();
        bos.close();
        File f=new File(path+"\\"+createTofileName);
        fundFeneSureBook.setFileSize(f.length()+"");
        System.out.println("生成认购书生成成功。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"+path+"\\"+createTofileName);
        return fundFeneSureBook;
    }
    public static FundFeneSureBook createPdfJingZhiLei(FundFeneSureBook fundFeneSureBook) throws IOException, DocumentException {
        // pdf模板
        /*  String fileName = "D:\\work\\ylcaifu\\智能投顾二期\\报表平台\\pdf生成好的不带logo的模板\\优策月月盈3号份额确认书-（追加申购模板）2.pdf";*/
        String fileName=fundFeneSureBook.getSourcePath();
        PdfReader reader = new PdfReader(fileName);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /* 将要生成的目标PDF文件名称 */
        PdfStamper ps = new PdfStamper(reader, bos);
        PdfContentByte under = ps.getUnderContent(1);
        /* 使用中文字体 */
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);
        /* 取出报表模板中的所有字段 */
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        fillData(fields, jingZhiProdData(fundFeneSureBook));
        /* 必须要调用这个，否则文档不会生成的 */
        ps.setFormFlattening(true);
        ps.close();
        //获取当天日期
        String today= DateUtil.getToDay();
        String l_storageid=fundFeneSureBook.getlStorageid();
        String targetPath=fundFeneSureBook.getTargetPath();
        String path=targetPath+today;
        boolean flag=FileUtils.mkdir(path);
        if(!flag){
            path=path+"\\Tblobstorage";
            //   file=new File(path);
            flag=FileUtils.mkdir(path);
        }else{
            path=path+"\\Tblobstorage";
        }
        String lStorageId=l_storageid.substring(0,l_storageid.length()-1);
        path=path+"\\"+lStorageId;
        FileUtils.mkdir(path);
        String createTofileName=l_storageid+"baccessory";
        FileUtils.createParentDir(path+"\\"+createTofileName);
        //生成pdf路径
        OutputStream fos = new FileOutputStream(path+"\\"+createTofileName);
        fos.write(bos.toByteArray());
        fos.flush();
        fos.close();
        bos.close();
        File f=new File(path+"\\"+createTofileName);
        fundFeneSureBook.setFileSize(f.length()+"");
        System.out.println("生成认购书生成成功。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"+path+"\\"+createTofileName);
        return fundFeneSureBook;
    }
    /**
     * 填充模板
     * */
    public static void fillData(AcroFields fields, Map<String, String> data)
            throws IOException, DocumentException {
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (!key.startsWith("Image")){
                //设置文本域参数值
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
            }else{
                //将图片写入指定的field
                      /*   Image image = Image.getInstance("D:\\work\\learn\\itext-master\\seal.png");
                         //将图片写入指定的field
                         PushbuttonField pb = fields.getNewPushbuttonFromField(key);
                         pb.setImage(image);
                         fields.replacePushbuttonField(key, pb.getField());*/

            }
        }
    }

    /**
     * 填充数据源 净值类产品（手动同步和自动同步2中，cyType只代表是申购还是追加）
     * 其中data存放的key值与pdf模板中的文本域值相对应
     * */
    public static Map<String, String> jingZhiProdData(FundFeneSureBook fundFeneSureBook) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userName", fundFeneSureBook.getUserName());
        String cyType=fundFeneSureBook.getCyType();
        //将合同编号取后三位
        String htNo=fundFeneSureBook.getHtNo();
        if(FundFeneSureBookContants.CON_TYP_STATUS_02.equals(cyType)){
           // htNo= htNo.substring(htNo.length()-3);
        }
        data.put("bianhao", htNo);
        //产品名称
        data.put("prodNm", fundFeneSureBook.getProdNm());//产品名称
        String feneDengJiDate=fundFeneSureBook.getFeneDengJiDate();
        if(!"".equals(feneDengJiDate)&&null!=feneDengJiDate&&feneDengJiDate.contains("-")){
            String feneDengJiDateArray[]=feneDengJiDate.split("-");
            if(feneDengJiDateArray.length==3){
                data.put("year", feneDengJiDateArray[0]);
                data.put("month",feneDengJiDateArray[1]);
                data.put("day", feneDengJiDateArray[2]);
            }
        }

        //小写金额转大写金额
        String bigMoney=fundFeneSureBook.getRgBigMoney();
        if(""!=bigMoney&&null!=bigMoney){
            double moneyDouble=Double.parseDouble(bigMoney);
            String MONEY=MoneyTool.change(moneyDouble);
            if(MONEY.contains("元整")){
                MONEY=MONEY.replace("元整","");
            }
            if(MONEY.contains("千")){
                MONEY=MONEY.replace("千","仟");
            }
            data.put("MONEY",MONEY);
        }

        data.put("money", MoneyTool.formatTosepara(Double.parseDouble(fundFeneSureBook.getRgSmallMoney())));
        data.put("fene",  MoneyTool.formatTosepara(Double.parseDouble(fundFeneSureBook.getRgFene())));
        data.put("shengoufei", fundFeneSureBook.getFen());
        String signDate=fundFeneSureBook.getSignDate();
        //此日期需要修改为份额确认日后的第二个工作日
       // String workDay=DateUtil.getWorkDay(signDate,2);
        String workDay=signDate;
        if(!"".equals(workDay)&&null!=workDay&&workDay.contains("-")){
            String workDayArrau[]=workDay.split("-");
            if(workDayArrau.length==3){
                data.put("yearBottom",workDayArrau[0]);
                data.put("monthBottom",workDayArrau[1]);
                data.put("dayBottom", workDayArrau[2]);
            }

        }

        return data;
    }
    public static void main(String args[]){
        String fileName2="优策长秀1号私募证券投资基金份额确认书-（第一次申购模板）盖章.pdf";
        String fileName="优策长实1号私募证券投资基金份额确认书-（追加申购模板）盖章.pdf";
        try {
            PdfReader reader = new PdfReader(fileName);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            PdfContentByte under = ps.getUnderContent(1);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();

            fields.setSubstitutionFonts(fontList);
            //fillData(fields, jingZhiProdData(fundFeneSureBook));
            /* 必须要调用这个，否则文档不会生成的 */
            ps.setFormFlattening(true);
            ps.close();
            //获取当天日期
            String today= DateUtil.getToDay();
           String l_storageid="12345";
            String targetPath="D:\\fundcrm\\djcrmuat";
            String path=targetPath+today;
            boolean flag=FileUtils.mkdir(path);
            if(!flag){
                path=path+"\\Tblobstorage";
                //   file=new File(path);
                flag=FileUtils.mkdir(path);
            }else{
                path=path+"\\Tblobstorage";
            }
            String lStorageId=l_storageid.substring(0,l_storageid.length()-1);
            path=path+"\\"+lStorageId;
            FileUtils.mkdir(path);
            String createTofileName=l_storageid+"baccessory";
            FileUtils.createParentDir(path+"\\"+createTofileName);
            //生成pdf路径
            OutputStream fos = new FileOutputStream(path+"\\"+createTofileName);
            fos.write(bos.toByteArray());
            fos.flush();
            fos.close();
            bos.close();
            File f=new File(path+"\\"+createTofileName);
           System.out.println("size============================"+f.length()+"");
            System.out.println("生成认购书生成成功。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"+path+"\\"+createTofileName);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
